package com.pond.pond.controller;

import com.pond.common.core.web.controller.BaseController;
import com.pond.common.core.web.domain.AjaxResult;
import com.pond.common.core.web.page.TableDataInfo;
import com.pond.common.log.annotation.Log;
import com.pond.common.log.enums.BusinessType;
import com.pond.common.security.annotation.RequiresPermissions;
import com.pond.pond.domain.PondOrder;
import com.pond.pond.domain.dto.CreateOrderRequest;
import com.pond.pond.domain.dto.OrderQueryRequest;
import com.pond.pond.domain.vo.OrderVO;
import com.pond.pond.service.IPondOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 订单管理控制器
 */
@Tag(name = "订单管理", description = "订单相关接口")
@RestController
@RequestMapping("/order")
@Validated
public class PondOrderController extends BaseController {
    
    @Autowired
    private IPondOrderService pondOrderService;
    
    /**
     * 查询订单列表
     */
    @Operation(summary = "查询订单列表")
    @RequiresPermissions("pond:order:list")
    @GetMapping("/list")
    public TableDataInfo list(OrderQueryRequest query) {
        startPage();
        List<OrderVO> list = pondOrderService.selectOrderList(query);
        return getDataTable(list);
    }
    
    /**
     * 根据订单ID查询订单详情
     */
    @Operation(summary = "查询订单详情")
    @RequiresPermissions("pond:order:query")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@Parameter(description = "订单ID") @PathVariable Long id) {
        OrderVO orderVO = pondOrderService.selectOrderById(id);
        return orderVO != null ? AjaxResult.success(orderVO) : AjaxResult.error("订单不存在");
    }
    
    /**
     * 根据订单编号查询订单
     */
    @Operation(summary = "根据订单编号查询订单")
    @RequiresPermissions("pond:order:query")
    @GetMapping("/orderNo/{orderNo}")
    public AjaxResult getByOrderNo(@Parameter(description = "订单编号") @PathVariable String orderNo) {
        PondOrder order = pondOrderService.selectByOrderNo(orderNo);
        return order != null ? AjaxResult.success(order) : AjaxResult.error("订单不存在");
    }
    
    /**
     * 创建订单（预约签到后自动创建）
     */
    @Operation(summary = "预约签到后创建订单")
    @RequiresPermissions("pond:order:add")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping("/createFromAppointment/{appointmentSegmentId}")
    public AjaxResult createFromAppointment(
            @Parameter(description = "预约时间段ID") @PathVariable Long appointmentSegmentId) {
        return pondOrderService.createOrderFromAppointment(appointmentSegmentId);
    }
    
    /**
     * 创建订单（管理员直接创建）
     */
    @Operation(summary = "管理员直接创建订单")
    @RequiresPermissions("pond:order:add")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping("/createDirect")
    public AjaxResult createDirect(@Valid @RequestBody CreateOrderRequest request) {
        return pondOrderService.createOrderDirect(request);
    }
    
    /**
     * 更新订单状态
     */
    @Operation(summary = "更新订单状态")
    @RequiresPermissions("pond:order:edit")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/status/{status}")
    public AjaxResult updateStatus(
            @Parameter(description = "订单ID") @PathVariable Long id,
            @Parameter(description = "订单状态") @PathVariable Integer status) {
        return pondOrderService.updateOrderStatus(id, status);
    }
    
    /**
     * 完成订单
     */
    @Operation(summary = "完成订单")
    @RequiresPermissions("pond:order:edit")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/complete")
    public AjaxResult complete(@Parameter(description = "订单ID") @PathVariable Long id) {
        return pondOrderService.completeOrder(id);
    }
    
    /**
     * 取消订单
     */
    @Operation(summary = "取消订单")
    @RequiresPermissions("pond:order:edit")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/cancel")
    public AjaxResult cancel(
            @Parameter(description = "订单ID") @PathVariable Long id,
            @Parameter(description = "取消原因") @RequestParam(required = false) String reason) {
        return pondOrderService.cancelOrder(id, reason);
    }
    
    /**
     * 删除订单（支持批量删除）
     */
    @Operation(summary = "删除订单（支持批量删除）")
    @RequiresPermissions("pond:order:remove")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@Parameter(description = "订单ID，多个ID用逗号分隔") @PathVariable String ids) {
        return pondOrderService.deleteOrders(ids);
    }
    
    /**
     * 添加订单项
     */
    @Operation(summary = "添加订单项")
    @RequiresPermissions("pond:order:edit")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{orderId}/item")
    public AjaxResult addOrderItem(
            @Parameter(description = "订单ID") @PathVariable Long orderId,
            @Valid @RequestBody CreateOrderRequest.OrderItemRequest request) {
        return pondOrderService.addOrderItem(orderId, request);
    }
    
    /**
     * 更新订单项支付状态
     */
    @Operation(summary = "更新订单项支付状态")
    @RequiresPermissions("pond:order:edit")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping("/item/{itemId}/pay")
    public AjaxResult updateItemPayStatus(
            @Parameter(description = "订单项ID") @PathVariable Long itemId,
            @Parameter(description = "支付状态") @RequestParam Integer payStatus,
            @Parameter(description = "支付方式") @RequestParam(required = false) Integer payType) {
        return pondOrderService.updateOrderItemPayStatus(itemId, payStatus, payType);
    }
    
    /**
     * 查询未完成订单列表（用于回鱼操作）
     */
    @Operation(summary = "查询未完成订单列表")
    @RequiresPermissions("pond:order:list")
    @GetMapping("/unfinished")
    public TableDataInfo getUnfinishedOrders(OrderQueryRequest query) {
        // 设置查询条件为未完成状态
        query.setStatus(0);
        startPage();
        List<OrderVO> list = pondOrderService.selectOrderList(query);
        return getDataTable(list);
    }
    
    /**
     * 生成订单编号
     */
    @Operation(summary = "生成订单编号")
    @RequiresPermissions("pond:order:query")
    @GetMapping("/generateOrderNo")
    public AjaxResult generateOrderNo() {
        String orderNo = pondOrderService.generateOrderNo();
        return AjaxResult.success("订单编号生成成功", orderNo);
    }
}